package exchange;

import main.Chat;

import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.FixedSetPrompt;
import org.bukkit.conversations.Prompt;
import org.bukkit.entity.Player;

import economy.Money;

public class TransactionPrompt extends FixedSetPrompt {
	
	public TransactionPrompt() {
		super("yes", "no", "cancel");
	}

	@Override
	public String getPromptText(ConversationContext context) {
		String type = (String) context.getSessionData("type");
		Item item = (Item) context.getSessionData("item");
		int quantity = (int) context.getSessionData("quantity");
		int price = (int) context.getSessionData("price");
		String transaction = type + " " + quantity + " " + item.getName();
		transaction = transaction + (quantity > 1? "s" : "");
		return "Do you wish to " + transaction + " for $" + price + "?";
	}

	@Override
	public boolean isInputValid(ConversationContext context, String input) {		
		switch (input.toLowerCase()) {
		case "/y":
		case "/yes":
		case "/n":
		case "/no":
		case "/cancel":
			return true;
		default:
			return false;				
		}
	}

	@Override
	protected Prompt acceptValidatedInput(ConversationContext context, String input) {
		Player player = (Player) context.getForWhom();
		ItemList itemList = (ItemList) context.getSessionData("items");
		Item item = (Item) context.getSessionData("item");
		int quantity = (int) context.getSessionData("quantity");
		Money money = (Money) player.getMetadata("QConomy").get(0);
		String type = (String) context.getSessionData("type");
		int price = (int) context.getSessionData("price");
		switch (input.toLowerCase()) {
		case "/y":
		case "/yes":
			if (type.equals("buy")) {
				money.withdraw(price);
				player.getInventory().addItem(item.getItemStack(quantity));
				context.setSessionData("reset", 0);
			}
			else if (type.equals("sell")) {
				money.deposit(price);
				player.getInventory().removeItem(item.getItemStack(quantity));
				item.increaseQuantity(quantity);
			}
			player.sendMessage(Chat.GREEN + "Sale successful!");
			player.sendMessage(Chat.GREEN + "Your balance is now " + money.toString());
			return new ExchangePrompt(itemList);
		case "/n":
		case "/no":
		case "/cancel":
			return new ExchangePrompt(itemList);
		default:
			return Prompt.END_OF_CONVERSATION;
		}
	}
}
